// pages/index/canvas/canvas.js
var app = getApp();
import Api from '../../../api/api.js';
var app = getApp();
const api = new Api();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    realHeight: 475,
    realWidth: 375,
    height: 617,
    scale: 1,
    canvasType: "",
    detailData: {},
    headimg: "",
    ecodeQImage: null,
    imageList: [],
    imageCount: 0,
    imageTop: 0,
    imageBottom: 0,
    whiteTop: 0,
    votes:null,
    userDetailData:null,
    voteTotalCount:0,
    isVote:false,
    headHeight:96,


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var width = wx.getSystemInfoSync().windowWidth;
    this.data.scale = width / 375;
    var heigth = wx.getSystemInfoSync().windowHeight;
    this.setData({
      height: heigth,
      realHeight: 700 * this.data.scale,
      realWidth: width
    });
    var string = wx.getStorageSync("canvasData");
    console.log(string);
    var dict = JSON.parse(string);
    this.data.detailData = dict;
    var imgs = dict.post.imgs;
    this.data.imageCount = imgs.length;
    this.getHeadImage(dict.headimg);
    // 下载图片
    this.getPostImages(imgs);
    this.getCodeQ(dict.post.id);
    this.getUserData(dict.post.userId);
  },
  getUserData(userId) {
    var _this = this;
    var map = {};
    map.appId = app.APP_ID;
    map.userId = userId;
    api.getRequestDataNoLoading(app.getUserDataByUserIdUrl, map, false, "GET").then(res => {
      _this.setData({
        userDetailData: res
      });
      _this.beginDrawImage();

    });
  },
  getCodeQ(postId) {
    var _this = this;
    var map = {};
    map.param = postId + "";
    map.page = "pages/index/detail/detail";
    api.getRequestData(app.getQR, map, false).then(res => {
      if (res.data.errorCode == 0) {
        var qr = res.data.model;
        var array = qr.split(":");
        array[0] = "https:";
        var downUrl = "";
        for (var i = 0; i < array.length; i++) {
          downUrl += array[i];
        }

        wx.downloadFile({
          url: downUrl,
          success: function (res) {
            _this.data.ecodeQImage = res.tempFilePath;
            _this.beginDrawImage();
          }, fail: function (res) {
          }
        })
      } else {
        app.alert(res.data.msg);

      }
    });
  },
  getHeadImage(url) {
    var _this = this;
    wx.downloadFile({
      url: url,
      success: function (res) {
        _this.data.headimg = res.tempFilePath;
        _this.beginDrawImage();
      }, fail: function (res) {
      }
    })
  },
  getPostImages(imgs) {
    var _this = this;
    for (var i = 0; i < imgs.length; i++) {
      var url = imgs[i];
      wx.downloadFile({
        url: url,
        success: function (res) {
          _this.data.imageList.push(res.tempFilePath);
          _this.beginDrawImage();
        }, fail: function (res) {
        }
      })
    }
  },
  beginDrawImage() {
    // && this.data.ecodeQImage
    if (this.data.headimg.length > 0 && this.data.imageList.length == this.data.imageCount && this.data.userDetailData ) {
      this.beginDraw()
    }
  },
  realDistance(distance) {
    return this.data.scale * distance;
  },
  beginDraw() {
    var context = wx.createCanvasContext('myCanvas');
    wx.showLoading({
      title: '绘制中...',
    });
    var postDict = this.data.detailData.post;
    var contentText = postDict.content;
    // 计算图片高度
    var imageList = this.data.imageList;
    var votes = this.data.detailData.votes;
    // 最后改版后的画布
    var description = '';
    this.data.headHeight = this.realDistance(75);
    if (this.data.userDetailData.description){
      description = this.data.userDetailData.description;
      if (description.length > 0) {
        this.getNeedHeadHeight(context, description, 0, 0, false);
      }
    }
    this.drawContentText(context, contentText, this.realDistance(20), this.data.headHeight / 2 + this.realDistance(98), false);
    this.data.imageTop +=  this.realDistance(30);
    this.data.imageBottom = this.data.imageTop;
    if (imageList.length == 1 || votes) {
      if (votes){
        // 计算head高度
        for (var i = 0; i < votes.length; i++) {
          var voteItem = votes[i];
          this.data.voteTotalCount += parseFloat(voteItem.vote.voteQty + "");
        }
        this.data.voteTotalCount = this.getNeedCount(this.data.voteTotalCount);
        this.data.votes = votes;
        // 说明有投票
        var length = votes.length;
        if (length > 5) {
          length = 5;
        }
        this.data.imageBottom = this.data.imageTop + this.realDistance(80) + length * this.realDistance(30) + this.realDistance(8) * (length - 1);
  
      } else {
        this.data.imageBottom = this.data.imageTop + this.realDistance(160);
      }
      this.drawContxt(context);
  
    } else {

       if (imageList.length == 4) {
        var imageW = (this.data.realWidth - this.realDistance(40) - this.realDistance(15)) / 2.0;
        for (var i = 0; i < imageList.length; i++) {
          var url = imageList[i];
          var ih = parseInt(i / 2);
          if (i == imageList.length - 1) {
            this.data.imageBottom = this.data.imageTop + (imageW + this.realDistance(15)) * ih + imageW;
          }
        }
      } else {
        var imageW = (this.data.realWidth - this.realDistance(40) - this.realDistance(20)) / 3.0;
        for (var i = 0; i < imageList.length; i++) {
          var url = imageList[i];
          var ih = parseInt(i / 3);
          if (i == imageList.length - 1) {
            this.data.imageBottom = this.data.imageTop + (imageW + this.realDistance(10)) * ih + imageW;
          }
        }
      }
    }
    this.drawContxt(context);
    context.draw();
    wx.hideLoading();
  },
  drawContxt(context) {
    // 绘制背景
    context.setFillStyle('#E97D6B')
    context.fillRect(0, 0, this.data.realWidth, this.realDistance(160) + this.data.imageBottom);
    this.setData({
      realHeight: this.realDistance(160) + this.data.imageBottom
    });
    context.setFillStyle('white')
    context.fillRect(0, this.realDistance(98), this.data.realWidth, this.data.imageBottom - this.realDistance(50));

    context.setFillStyle('white')
    context.setShadow(0, 0, 4, 'rgba(175,160,157,0.3)');
    var top = this.realDistance(98) - this.data.headHeight / 2;
    context.fillRect(this.realDistance(20), top, this.data.realWidth - this.realDistance(40), this.data.headHeight);

    this.data.whiteTop = this.realDistance(50) + this.data.imageBottom;
    context.setShadow(0, 0, 0, 'black');

    context.save();
    var postDict = this.data.detailData.post;
    var top = this.realDistance(98) - this.data.headHeight / 2;

//     context.arc(this.realDistance(56), this.realDistance(32.5) + top, this.realDistance(20), 0, Math.PI * 2, false);
//     context.clip();
//  context.setFillStyle("white");
//     context.fill();
    context.drawImage(this.data.headimg, this.realDistance(36), this.realDistance(12.5) + top, this.realDistance(40), this.realDistance(40));
    context.restore();
    context.save();
    //画昵称
    var nickName = this.data.detailData.nickname;
    context.setFontSize(this.realDistance(15))
    context.setFillStyle("#262626");
    context.fillText(nickName, this.realDistance(86), this.realDistance(25) + top);
    context.restore();

    var followText = "关注" + this.data.userDetailData.followCount + " | " + "粉丝" + this.data.userDetailData.fansCount;
    var nickName = this.data.detailData.nickname;
    context.setFontSize(this.realDistance(11))
    context.setFillStyle("#909090");
    context.fillText(followText, this.realDistance(86), this.realDistance(42) + top);
    context.restore();
    var description = '';
    if (this.data.userDetailData.description){
      description = this.data.userDetailData.description;
    }
    this.getNeedHeadHeight(context, description, this.realDistance(86), this.realDistance(60) + top, true);

    // 绘制正文文本
    var contentText = postDict.content;
    var title = postDict.title;
    if (title.length > 0) {
      contentText = '【' + title + '】' + postDict.content;
    }
    this.drawContentText(context, contentText, this.realDistance(20), this.realDistance(98) + this.data.headHeight / 2 + this.realDistance(30), true);
    context.save();
    if (this.data.votes){
   // 绘制帖子
   context.setFillStyle('#F6F6F6')
   context.fillRect(this.realDistance(20), this.data.imageTop, this.data.realWidth - this.realDistance(40), this.data.imageBottom - this.data.imageTop);
   // voteTitle
   var voteTitle = this.data.detailData.post.voteTitle;
   context.setFillStyle("#262626");
   context.setFontSize(12 * this.data.scale);
   context.fillText(voteTitle, this.realDistance(32), this.data.imageTop + this.realDistance(20), this.data.realWidth - this.realDistance(64));

   var length = this.data.votes.length;
   if (length > 5) {
     length = 5;
   }
   for (var i = 0; i < length;i++) {
     var voteItem = this.data.votes[i];
     var title = voteItem.vote.content;

     context.setFillStyle('#FFFFFF')
     context.fillRect(this.realDistance(32), this.data.imageTop + this.realDistance(40) + this.realDistance(38) * i, this.data.realWidth - this.realDistance(64), this.realDistance(30));
     context.setFillStyle("#262626");
     context.setFontSize(11 * this.data.scale);
     context.fillText(title, this.realDistance(40), this.data.imageTop + this.realDistance(58) + this.realDistance(38) * i, this.data.realWidth - this.realDistance(80));
     
     if (i == length -1) {
       context.setFillStyle("#8F8F8F");
       context.setFontSize(11 * this.data.scale);
       var endTime = this.data.voteTotalCount+"人参与" +"  "+ this.getDateTime(this.data.detailData.post.endTime)+"结束";
       context.fillText(endTime, this.realDistance(32), this.data.imageTop + this.realDistance(95) + this.realDistance(38) * i, this.data.realWidth - this.realDistance(64));
     }
   }
    } else {
     // 开始绘制帖子图片
     var imageList = this.data.imageList;
     if (imageList.length == 1) {
       context.drawImage(imageList[0], this.realDistance(20), this.data.imageTop, this.data.realWidth - this.realDistance(40), this.realDistance(160));

       context.restore();
     } else if (imageList.length == 4) {
       var imageW = (this.data.realWidth - this.realDistance(40) - this.realDistance(15)) / 2.0;
       for (var i = 0; i < imageList.length; i++) {
         var url = imageList[i];
         var ih = parseInt(i / 2);
         context.drawImage(url, this.realDistance(20) + (imageW + this.realDistance(15)) * (i % 2), this.data.imageTop + (imageW + this.realDistance(15)) * ih, imageW, imageW);
       }
     } else {
       var imageW = (this.data.realWidth - this.realDistance(40) - this.realDistance(20)) / 3.0;
       for (var i = 0; i < imageList.length; i++) {
         var url = imageList[i];
         var ih = parseInt(i / 3);
         context.drawImage(url, this.realDistance(20) + (imageW + this.realDistance(10)) * (i % 3), this.data.imageTop + (imageW + this.realDistance(10)) * ih, imageW, imageW);
       }
     }
     context.restore();
    }

    // 绘制阅读打赏等
    var readCount = this.getNeedCount(postDict.readCount);
    var left = this.realDistance(20);
    readCount = readCount + "次阅读";
    context.setFontSize(13 * this.data.scale)
    context.setFillStyle("#9B9292");
    var readCountW = context.measureText(readCount).width;
    context.fillText(readCount, left, this.data.imageBottom + this.realDistance(25), readCount);

    // 开始绘制分享打赏次数
    var shareCount = this.getNeedCount(postDict.shareCount);
    shareCount = "分享" + shareCount;

    var rewardCount = this.getNeedCount(postDict.reward);
    rewardCount = "打赏" + rewardCount;

    var evaluateCount = this.getNeedCount(postDict.replyCount);
    evaluateCount = "评论" + evaluateCount;

    var agreeCount = this.getNeedCount(postDict.agreeCount);
    agreeCount = "赞" + agreeCount;

    context.setFillStyle("#262626");

    var rewardCountW = context.measureText(rewardCount).width;
    var shareCountW = context.measureText(shareCount).width;
    var evaluateCountW = context.measureText(evaluateCount).width;
    var agreeCountW = context.measureText(agreeCount).width;

    left = this.data.realWidth - this.realDistance(20) - this.realDistance(15) * 3 - rewardCountW - shareCountW - evaluateCountW - agreeCountW;
    context.fillText(shareCount, left, this.data.imageBottom + this.realDistance(25), shareCountW);

    left = this.data.realWidth - this.realDistance(20) - this.realDistance(15) * 2 - shareCountW - evaluateCountW - agreeCountW;
    context.fillText(rewardCount, left, this.data.imageBottom + this.realDistance(25), rewardCountW);

    left = this.data.realWidth - this.realDistance(20) - this.realDistance(15) - evaluateCountW - agreeCountW;
    context.fillText(evaluateCount, left, this.data.imageBottom + this.realDistance(25), evaluateCountW);

    left = this.data.realWidth - this.realDistance(20) - agreeCountW;
    context.fillText(agreeCount, left, this.data.imageBottom + this.realDistance(25), agreeCountW);

    // 开始绘制底部视图
    var des = "宠物帮｜有料";
    context.setFontSize(15 * this.data.scale)
    context.setFillStyle("white");
    var desW = context.measureText(des).width;
    context.fillText(des, this.realDistance(20), this.data.whiteTop + this.realDistance(45), desW);

    var desText = "铲屎官专属交流/分享/爆料平台";
    context.setFontSize(12 * this.data.scale)
    context.setFillStyle("white");
    var desTextW = context.measureText(desText).width;
    context.fillText(desText, this.realDistance(20), this.data.whiteTop + this.realDistance(76), desTextW);
    context.save();
    //绘制小程序码
    context.arc(this.data.realWidth - this.realDistance(54), this.data.whiteTop + this.realDistance(59), this.realDistance(34), 0, Math.PI * 2, false);
    context.clip();
    context.setFillStyle("white");
    context.fill();

    context.drawImage(this.data.headimg, this.data.realWidth - this.realDistance(88), this.data.whiteTop + this.realDistance(25), this.realDistance(68), this.realDistance(68));
    context.restore();



  },
  getNeedCount(count) {
    var count = parseFloat(count + "");
    if (count >= 10000) {
      count = count / 10000.0;
      count.toFixed(1);
      count = count + "万";
    } else {
      count.toFixed(0);
    }
    return count;
  },
  drawContentText(context, text, x, y, needCanvas) {
    var chr = text.split("");
    var temp = "";
    var row = [];
    context.setFontSize(14);
    context.setFillStyle("rgba(0,0,0,0.85)");
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < this.data.realWidth - this.realDistance(40)) {
        temp += chr[a];
      } else {
        a--;
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);

    //如果数组长度大于3 则截取前两个
    if (row.length > 3) {
      var rowCut = row.slice(0, 3);
      var rowPart = rowCut[2];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < this.data.realWidth - this.realDistance(40)) {
          test += rowPart[a];
        }
        else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..."
      rowCut.splice(2, 2, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      if (needCanvas) {
        context.fillText(row[b], x, y + b * this.realDistance(22), this.data.realWidth - this.realDistance(40));
      } else {
        this.data.imageTop = y + b * this.realDistance(22) + this.realDistance(30);
      }
    }
  },
  getNeedHeadHeight(context, text,x,y, needCanvas) {
    var chr = text.split("");
    var temp = "";
    var row = [];
    context.setFontSize(11);
    context.setFillStyle("#909090");
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < this.realDistance(253)) {
        temp += chr[a];
      } else {
        a--;
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);

    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < this.realDistance(253)) {
          test += rowPart[a];
        }
        else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..."
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      if (needCanvas) {
        context.fillText(row[b], x, y + b * this.realDistance(15), this.realDistance(253));
      } else {
        this.data.headHeight = b * this.realDistance(15) + this.realDistance(75);
      }
    }
  },
  saveImageToAum: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function (res) {
        var tempPath = res.tempFilePath;
        wx.saveImageToPhotosAlbum({
          filePath: tempPath,
          success: function success(resd) {
            console.log('saved::' + resd.savedFilePath);
            wx.showToast({
              title: "保存成功",
              icon: 'success',
              duration: 1500
            });
          },
          complete: function fail(e) {
          }
        });
      },
      fail: function (res) {

      }
    }, this)
  },
  getDateTime(date) {
    var d = new Date(date);
    var month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
    var day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
    var hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
    var min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
    // var sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
    var times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min;
    var year = d.getFullYear() + "";
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear() + "";
    if (nowYear == year) {
      times = month + '-' + day + ' ' + hours + ':' + min;
      return times;
    } else {
      return times;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // wx.removeStorageSync("canvasData");

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})